package com.summer.mida;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gson.Gson;

public class MidaTest {

	public static void main(String[] args) throws IOException {
		List<String> urls = readFileToUrl("C:/tmp/urls.txt");
		for(String url : urls){
			String realUrl = getRealUrl(url);
			RecordDetailParamsVO vo = parsingRealUrl(realUrl);
			String detailUrl = getRecordDetailUrl(vo.uid,vo.uuid,vo.jobid);
			String detailText = getDetail(detailUrl);
			RecordDetailEntity entity = new Gson().fromJson(detailText, RecordDetailEntity.class);
			download(entity);
			
			System.out.println("歌曲："+entity.data.record.song_name);
			System.out.println("表演者:"+entity.data.user_name);
			System.out.println("http://"+entity.data.record.domain+"/"+entity.data.record.url);
		}
		
	}
	
	/**
     * 读取一个文本 一行一行读取
     *
     * @param path
     * @return
     * @throws IOException
     */
	public static List<String> readFileToUrl(String path) throws IOException{
		 // 使用一个字符串集合来存储文本中的路径 ，也可用String []数组
        List<String> list = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(path);
        // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null) {
            // 如果 t x t文件里的路径 不包含---字符串       这里是对里面的内容进行一个筛选
            if (line.lastIndexOf("---") < 0) {
                list.add(line);
            }
        }
        br.close();
        isr.close();
        fis.close();
        return list;
	}
	
	public static String download(RecordDetailEntity entity) throws FileNotFoundException{
		String path= "./music";
		String url = "http://"+entity.data.record.domain+"/"+entity.data.record.url;
		
		HttpConnectionUtil.downloadFile(url, path,entity.data.record.song_name+"_"+entity.data.user_name);
		
		
		return path;
	}
	
	public static String getRealUrl(String shortUrl) throws IOException{
		String realUrl=null;
		if(shortUrl.contains("weixin.singworld.cn"))
			return shortUrl;
		URL url = new URL(shortUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.getResponseCode();
		realUrl = conn.getURL().toString();
		conn.disconnect();
		return realUrl;
	} 
	
	public static RecordDetailParamsVO parsingRealUrl(String realUrl){
		
		if(realUrl==null || realUrl.length()<=0)
			return null;
		
		RecordDetailParamsVO vo = new RecordDetailParamsVO();
		
		String[] tmpStr = realUrl.split("[?]");
		String[] valueStrs = tmpStr[1].split("&");
		for(String valueStr : valueStrs){
			if(valueStr.contains("/details/")){
				String[] tmps = valueStr.split("#");
				vo.jobid = tmps[1].replace("/details/", "").replace("--ml--", "");
			}
			if(valueStr.contains("uuid=")){
				String tmp = valueStr.replace("uuid=", "");
				String[] tmps = tmp.split("#");
				vo.uuid = tmps[0];
				continue;
			}
			if(valueStr.contains("uid=")){
				vo.uid = valueStr.replace("uid=", "");
				continue;
			}
		}
		
		return vo;
	}
	
	public static String getRecordDetailUrl(String uid,String uuid,String jobid){
		HashMap<String,String> params = new HashMap<String, String>();
		params.put("uid", uid);										//"85159"
		params.put("uuid", uuid);									//"9f8ac934-8b54-422c-9272-131713e52ffe"
		params.put("jobid", jobid);									//"3623_LOW_20181213193851_24589"
		params.put("token", "");
		params.put("user_from", "0");
		params.put("t", String.valueOf(System.currentTimeMillis()));//"1550929914604"

		StringBuilder builderUrl = new StringBuilder();
		builderUrl.append("https://weixin.singworld.cn/api/record/record_detail/?");
		
		for(String key : params.keySet()){
			String param = key +"="+params.get(key);
			builderUrl.append(param);
			builderUrl.append("&");
		}
		builderUrl.deleteCharAt(builderUrl.length()-1);
		return builderUrl.toString();
	}
	
	public static String getDetail(String detailUrl) {
		int Timeout = 5*1000;
		String encoding = "utf-8";//"gbk";
		String defaultValue = "";
		HttpURLConnection connection = null;
		InputStreamReader reader = null;
		BufferedReader l_reader = null;
		try {
			URL dataUrl = new URL(detailUrl);
			connection = (HttpURLConnection) dataUrl.openConnection();
			// 设置超时时间
			connection.setConnectTimeout(Timeout);
			connection.setReadTimeout(Timeout);
			//设置属性，如果不设置User-Agent可能会被某些网站当作爬虫过滤掉
			connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
			connection.connect();
			
			reader = new InputStreamReader(connection.getInputStream(),encoding);
			l_reader = new BufferedReader(reader);

			String sCurrentLine = "";
			String sTotalString = "";
			while ((sCurrentLine = l_reader.readLine()) != null) {
				sTotalString = sTotalString + sCurrentLine;
			}
			return sTotalString;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != l_reader) {l_reader.close();}
				if (null !=   reader) {reader.close();}
			} catch (IOException e)   {e.printStackTrace();}
			connection.disconnect();
		}
		return defaultValue;
	}
	
	
	public static class RecordDetailParamsVO{
		private String uid;
		private String uuid;
		private String jobid;
	}
	
	public static class RecordDetailEntity{
		public DataEnetity data;
		public class DataEnetity{
			public Record record;
			public String user_name;			//: "瓦斯",
			public class Record{
				public String song_name;		//: "下雨天"
				public String domain;			//: "ossaudio.singworld.cn"
				public String url;				//: "28/58/2312_LOW_20190223220546_90912_0.aac"
			}
		}
	}

}
